﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;
using BanZuiCloudControlAgent.Automation;
using BanZuiCloudControlAgent.Core.QQ;
using BanZuiCloudControlAgent.Extensions.QQ;
using BanZuiCloudControlAgent.Utils.Common;
using BanZuiCloudControlAgent.Utils.Logging;

namespace BanZuiCloudControlAgent.UI
{
    public partial class TestViewer : UserControl
    {
        private static Logger _logger;

        private QQAutomation _qqAutomation;

        private QQTest _qqTest;

        public TestViewer()
        {
            InitializeComponent();
            _logger = LogManager.GetLogger(nameof(TestViewer));
            _qqAutomation = new QQAutomation();
            _qqTest = new QQTest();
        }

        private void btnGetMenuStatus_Click(object sender, EventArgs e)
        {
            string pidStr = tbTestQQPID.Text.Trim(); // QQ进程ID
            // 转成整数
            if (!int.TryParse(pidStr, out int pid) || pid <= 0)
            {
                txtResult.Text = "请输入有效的QQ进程ID";
                return;
            }
            txtResult.Text = "开始执行检查群消息屏蔽状态...";

            try
            {
                bool? isBlocked = _qqAutomation.IsGroupMessageBlocked(pid);

                if (isBlocked == null)
                {
                    txtResult.Text += "\n无法确定群消息屏蔽状态";
                }
                else
                {
                    txtResult.Text +=
                        $"\n群消息屏蔽状态: {(isBlocked.Value ? "已屏蔽" : "未屏蔽")}";
                }
            }
            catch (Exception ex)
            {
                txtResult.Text += $"\n发生错误: {ex.Message}";
            }
        }

        private void btnGetLoginStatus_Click(object sender, EventArgs e)
        {
            string pidStr = tbTestQQPID.Text.Trim(); // QQ进程ID
            // 转成整数
            if (!int.TryParse(pidStr, out int pid) || pid <= 0)
            {
                txtResult.Text = "请输入有效的QQ进程ID";
                return;
            }

            bool isOnline = _qqAutomation.IsQQOnline(pid);
            txtResult.Text = $"QQ是否在线: {isOnline}";
        }

        /// <summary>
        /// 根据类名获取所有满足条件的窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetWindowsByClassName_Click(object sender, EventArgs e)
        {
            // 从设计器中添加的文本框获取类名
            GetWindowsByClassName(textBoxClassName.Text.Trim());
        }

        /// <summary>
        /// 根据类名查找所有满足条件的窗口
        /// </summary>
        /// <param name="className">要查找的窗口类名</param>
        private void GetWindowsByClassName(string className)
        {
            if (string.IsNullOrEmpty(className))
            {
                txtResult.Text = "请输入窗口类名";
                return;
            }

            txtResult.Text = $"开始查找类名为 '{className}' 的窗口...\r\n";

            try
            {
                // 使用Win32Api工具类查找指定类名的窗口
                List<IntPtr> windows = Win32Api.FindWindowsByClassName(className, true, false);

                foreach (IntPtr hWnd in windows)
                {
                    // 使用Win32Api获取窗口信息
                    WindowInfo info = Win32Api.GetWindowInfo(hWnd);
                    txtResult.Text += info.ToString() + "\r\n";
                }

                txtResult.Text += $"\r\n总共找到 {windows.Count} 个匹配的窗口";
            }
            catch (Exception ex)
            {
                txtResult.Text += $"\r\n查找窗口时出错: {ex.Message}";
            }
        }

        /// <summary>
        /// 测试QQ对象和QQManager
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnTestQQObject_Click(object sender, EventArgs e)
        {
            btnTestQQObject.Enabled = false;
            txtResult.Text = "开始测试QQ功能...\r\n";
            await _qqTest.TestQQManagerAsync();

            try
            {
                // 获取QQ进程ID（如果有输入）
                string pidStr = tbTestQQPID.Text.Trim();
                if (int.TryParse(pidStr, out int pid) && pid > 0)
                {
                    // 测试单个QQ实例
                    txtResult.AppendText($"测试QQ进程 (ID: {pid})...\r\n");

                    // 检查QQ是否在线
                    bool isOnline = _qqAutomation.IsQQOnline(pid);
                    txtResult.AppendText($"QQ在线状态: {(isOnline ? "在线" : "离线")}\r\n");

                    if (isOnline)
                    {
                        // 获取主窗口
                        var mainWindow = _qqAutomation.GetQQMainWindow(pid);
                        txtResult.AppendText(
                            $"主窗口: {(mainWindow != null ? "已找到" : "未找到")}\r\n"
                        );

                        // 获取群聊窗口
                        var groupWindow = _qqAutomation.GetGroupChatWindow(null, pid);
                        txtResult.AppendText(
                            $"群聊窗口: {(groupWindow != null ? "已找到" : "未找到")}\r\n"
                        );

                        // 检查群消息是否被屏蔽
                        var isBlocked = _qqAutomation.IsGroupMessageBlocked(pid);
                        if (isBlocked.HasValue)
                        {
                            txtResult.AppendText(
                                $"群消息屏蔽状态: {(isBlocked.Value ? "已屏蔽" : "未屏蔽")}\r\n"
                            );
                        }
                        else
                        {
                            txtResult.AppendText($"无法获取群消息屏蔽状态\r\n");
                        }
                    }
                    else
                    {
                        // 测试登录窗口
                        var loginWindow = _qqAutomation.GetLoginWindow();
                        txtResult.AppendText(
                            $"登录窗口: {(loginWindow != null ? "已找到" : "未找到")}\r\n"
                        );
                    }
                }
                else
                {
                    // 列出所有QQ进程
                    txtResult.AppendText("查找所有QQ进程...\r\n");
                    var processes = Process.GetProcessesByName("QQ");
                    txtResult.AppendText($"找到 {processes.Length} 个QQ进程:\r\n");

                    foreach (var process in processes)
                    {
                        try
                        {
                            bool isOnline = _qqAutomation.IsQQOnline(process.Id);
                            txtResult.AppendText(
                                $"- 进程ID: {process.Id}, 状态: {(isOnline ? "在线" : "离线")}\r\n"
                            );
                        }
                        catch (Exception ex)
                        {
                            txtResult.AppendText(
                                $"- 进程ID: {process.Id}, 检查出错: {ex.Message}\r\n"
                            );
                        }
                    }

                    if (processes.Length == 0)
                    {
                        txtResult.AppendText("请先启动QQ然后再测试\r\n");
                    }
                }

                txtResult.AppendText("\r\n测试完成。");
            }
            catch (Exception ex)
            {
                txtResult.AppendText($"\r\n测试过程中发生错误: {ex.Message}");
            }
            finally
            {
                btnTestQQObject.Enabled = true;
            }
        }

        /// <summary>
        /// 从UI界面判断QQ是否在线
        /// </summary>
        /// <param name="targetProcessId">目标进程ID</param>
        /// <returns>是否在线</returns>
        private bool IsQQOnlineFromUI(int targetProcessId)
        {
            // 此方法的实现已移除，仅作为占位符保留
            return _qqAutomation.IsQQOnline(targetProcessId);
        }

        /// <summary>
        /// 获取QQ进程的所有窗口信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetQQProcessWindows_Click(object sender, EventArgs e)
        {
            string pidStr = tbTestQQPID.Text.Trim(); // QQ进程ID
            // 转成整数
            if (!int.TryParse(pidStr, out int pid) || pid <= 0)
            {
                txtResult.Text = "请输入有效的QQ进程ID";
                return;
            }

            txtResult.Text = $"开始获取QQ进程(ID: {pid})的所有窗口信息...\r\n";

            try
            {
                // 确认进程存在
                Process process;
                try
                {
                    process = Process.GetProcessById(pid);
                    if (process.ProcessName != "QQ")
                    {
                        txtResult.AppendText($"警告：进程ID {pid} 不是QQ进程，而是 {process.ProcessName}\r\n\r\n");
                    }
                }
                catch (ArgumentException)
                {
                    txtResult.AppendText($"错误：找不到进程ID为 {pid} 的进程\r\n");
                    return;
                }

                // 使用Win32Api查找该进程的所有窗口
                List<IntPtr> windows = Win32Api.FindWindowsByProcessId(pid, false);
                txtResult.AppendText($"找到 {windows.Count} 个窗口:\r\n\r\n");

                // 遍历所有窗口并获取详细信息
                foreach (IntPtr hWnd in windows)
                {
                    WindowInfo info = Win32Api.GetWindowInfo(hWnd);
                    txtResult.AppendText($"窗口句柄: 0x{hWnd.ToInt64():X8}\r\n");
                    txtResult.AppendText($"标题: {info.Title}\r\n");
                    txtResult.AppendText($"类名: {info.ClassName}\r\n");
                    txtResult.AppendText($"可见: {info.IsVisible}\r\n");
                    
                    // 获取窗口位置和大小
                    Win32Api.RECT rect;
                    if (Win32Api.GetWindowRectangle(hWnd, out rect))
                    {
                        int width = rect.Right - rect.Left;
                        int height = rect.Bottom - rect.Top;
                        txtResult.AppendText($"位置: ({rect.Left}, {rect.Top}) 大小: {width}x{height}\r\n");
                    }
                    
                    txtResult.AppendText("\r\n");
                }

                txtResult.AppendText("窗口信息获取完成。");
            }
            catch (Exception ex)
            {
                txtResult.AppendText($"\r\n获取窗口信息时出错: {ex.Message}");
                _logger.Error($"获取QQ进程窗口信息失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 测试QQ号码提取功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTestQQNumberExtraction_Click(object sender, EventArgs e)
        {
            string pidStr = tbTestQQPID.Text.Trim(); // QQ进程ID
            // 转成整数
            if (!int.TryParse(pidStr, out int pid) || pid <= 0)
            {
                txtResult.Text = "请输入有效的QQ进程ID";
                return;
            }

            txtResult.Text = $"开始测试QQ号码提取功能，进程ID: {pid}...\r\n";

            try
            {
                // 使用QQTest类测试QQ号码提取
                string qqNumber = _qqTest.TestQQNumberExtraction(pid);

                if (string.IsNullOrEmpty(qqNumber))
                {
                    txtResult.AppendText("未能提取到QQ号码，可能原因：\r\n");
                    txtResult.AppendText("1. 该进程不是QQ进程\r\n");
                    txtResult.AppendText("2. QQ窗口标题格式不符合预期\r\n");
                    txtResult.AppendText("3. 未找到包含QQ号码的窗口\r\n");
                    
                    // 列出所有窗口标题供分析
                    txtResult.AppendText("\r\n该进程的所有窗口标题：\r\n");
                    List<IntPtr> windows = Win32Api.FindWindowsByProcessId(pid, false);
                    foreach (IntPtr hWnd in windows)
                    {
                        string title = Win32Api.GetWindowTitle(hWnd);
                        txtResult.AppendText($"- {title}\r\n");
                    }
                }
                else
                {
                    txtResult.AppendText($"成功提取到QQ号码：{qqNumber}\r\n");
                    txtResult.AppendText("提取成功！");
                }
            }
            catch (Exception ex)
            {
                txtResult.AppendText($"\r\n测试QQ号码提取功能时出错: {ex.Message}");
                _logger.Error($"测试QQ号码提取功能失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 测试QQ扩展功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTestQQExtension_Click(object sender, EventArgs e)
        {
            string pidStr = tbTestQQPID.Text.Trim(); // QQ进程ID
            // 转成整数
            if (!int.TryParse(pidStr, out int pid) || pid <= 0)
            {
                txtResult.Text = "请输入有效的QQ进程ID";
                return;
            }

            txtResult.Text = $"开始测试QQ扩展功能，进程ID: {pid}...\r\n";

            try
            {
                // 获取QQ信息
                QQInfo qqInfo = QQExtension.GetQQInfo(pid);

                if (qqInfo == null)
                {
                    txtResult.AppendText("未能获取QQ信息，可能原因：\r\n");
                    txtResult.AppendText("1. 该进程不是QQ进程\r\n");
                    txtResult.AppendText("2. QQ未登录或不在线\r\n");
                    txtResult.AppendText("3. 无法获取QQ号码\r\n");
                    return;
                }

                // 显示QQ信息
                txtResult.AppendText("QQ信息获取成功：\r\n");
                txtResult.AppendText($"QQ号：{qqInfo.QQNumber}\r\n");
                txtResult.AppendText($"昵称：{qqInfo.Nickname ?? "未获取到"}\r\n");
                txtResult.AppendText($"进程ID：{qqInfo.ProcessId}\r\n");
                txtResult.AppendText($"在线状态：{(qqInfo.IsOnline ? "在线" : "离线")}\r\n");
                txtResult.AppendText($"群数量：{qqInfo.GroupList.Count}\r\n");
                
                // 显示群列表
                if (qqInfo.GroupList.Count > 0)
                {
                    txtResult.AppendText("\r\n群列表：\r\n");
                    foreach (var group in qqInfo.GroupList)
                    {
                        txtResult.AppendText($"- {group}\r\n");
                    }
                }
                
                // 显示Cookie信息（部分）
                if (!string.IsNullOrEmpty(qqInfo.Cookie))
                {
                    txtResult.AppendText("\r\nCookie信息（前50字符）：\r\n");
                    txtResult.AppendText($"{qqInfo.Cookie.Substring(0, Math.Min(50, qqInfo.Cookie.Length))}...\r\n");
                }
                else
                {
                    txtResult.AppendText("\r\n未获取到Cookie信息\r\n");
                }
                
                txtResult.AppendText("\r\nQQ扩展功能测试完成！");
            }
            catch (Exception ex)
            {
                txtResult.AppendText($"\r\n测试QQ扩展功能时出错: {ex.Message}");
                _logger.Error($"测试QQ扩展功能失败: {ex.Message}", ex);
            }
        }
        
        /// <summary>
        /// 测试QQ群组Web接口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnTestQQGroupWeb_Click(object sender, EventArgs e)
        {
            string pidStr = tbTestQQPID.Text.Trim(); // QQ进程ID
            // 转成整数
            if (!int.TryParse(pidStr, out int pid) || pid <= 0)
            {
                txtResult.Text = "请输入有效的QQ进程ID";
                return;
            }

            txtResult.Text = $"开始测试QQ群组Web接口，进程ID: {pid}...\r\n";
            
            try
            {
                // 从进程创建QQGroupWeb实例
                var qqGroupWeb =  QQGroupWeb.CreateFromProcessAsync(pid);
                if (qqGroupWeb == null)
                {
                    txtResult.AppendText("创建QQGroupWeb实例失败，无法获取Cookie\r\n");
                    return;
                }
                
                txtResult.AppendText("成功创建QQGroupWeb实例，开始获取群组数据...\r\n");
                
                // 获取群组模型
                var groupModel = await qqGroupWeb.GetGroupModelAsync();
                
                // 显示加入的群
                txtResult.AppendText("\r\n加入的群组：\r\n");
                if (groupModel.Join != null && groupModel.Join.Length > 0)
                {
                    foreach (var group in groupModel.Join)
                    {
                        txtResult.AppendText($"群号: {group.GroupNumber}, 群名: {group.GroupName}, 成员数: {group.MemberCount}/{group.MaxMemberCount}\r\n");
                    }
                }
                else
                {
                    txtResult.AppendText("没有加入任何群组\r\n");
                }
                
                // 显示管理的群
                txtResult.AppendText("\r\n管理的群组：\r\n");
                if (groupModel.Manage != null && groupModel.Manage.Length > 0)
                {
                    foreach (var group in groupModel.Manage)
                    {
                        txtResult.AppendText($"群号: {group.GroupNumber}, 群名: {group.GroupName}, 成员数: {group.MemberCount}/{group.MaxMemberCount}\r\n");
                    }
                }
                else
                {
                    txtResult.AppendText("没有管理任何群组\r\n");
                }
                
                // 显示创建的群
                txtResult.AppendText("\r\n创建的群组：\r\n");
                if (groupModel.Create != null && groupModel.Create.Length > 0)
                {
                    foreach (var group in groupModel.Create)
                    {
                        txtResult.AppendText($"群号: {group.GroupNumber}, 群名: {group.GroupName}, 成员数: {group.MemberCount}/{group.MaxMemberCount}\r\n");
                    }
                }
                else
                {
                    txtResult.AppendText("没有创建任何群组\r\n");
                }
                
                txtResult.AppendText("\r\nQQ群组Web接口测试完成！");
            }
            catch (Exception ex)
            {
                txtResult.AppendText($"\r\n测试QQ群组Web接口时出错: {ex.Message}");
                _logger.Error($"测试QQ群组Web接口失败: {ex.Message}", ex);
            }
        }
    }
}
